package oop.controller.action.test;

import java.sql.SQLException;
import java.util.List;

import oop.controller.action.DefaultAction;
import oop.data.Test;

import org.apache.commons.lang.StringUtils;

public class ListAction extends DefaultAction {

	public static final int PAGE_LENGTH = 30;

	@Override
	public void perform() throws Exception {
		String submitted = request.getParameter("tl_submit");
		if ("create".equals(submitted)) {
			setNextAction("test.create");
			return;
		} else if ("delete".equals(submitted)) {
			String[] items = request.getParameterValues("tl_tests");
			String mess = "";
			int deleted = 0;
			for (String item : items) {
				try {
					int id = Integer.parseInt(item);
					try {
						deleted += Test.drop(id);
					} catch (SQLException ex) {
						if (ex.getErrorCode() == 1451) {
							Test test = Test.fetchById(id).get(0);
							mess += "Không thể xóa đề thi đang sử dụng: "
									+ test.getName() + "<br />";
						} else {
							throw ex;
						}
					}
				} catch (NumberFormatException ex) {
					mess += "Id không hợp lệ: " + item + "<br />";
				}
			}
			if (deleted > 0) {
				mess += "Đã xóa " + deleted + " mục";
			}
			request.setAttribute("message", mess);
		}

		String pageStr = StringUtils.defaultIfEmpty(request
				.getParameter("page"), "1");
		int page = Integer.parseInt(pageStr);

		List<Test> tests;
		int count;
		if (request.getParameter("category") != null) {
			int id = Integer.parseInt(request.getParameter("category"));
			tests = Test.fetchByCategory(id, (page - 1) * PAGE_LENGTH,
					PAGE_LENGTH);
			count = Test.countByCategory(id);
		} else if (request.getParameter("author") != null) {
			int id = Integer.parseInt(request.getParameter("author"));
			tests = Test.fetchByAuthor(id, (page - 1) * PAGE_LENGTH,
					PAGE_LENGTH);
			count = Test.countByAuthor(id);
		} else {
			tests = Test.fetch((page - 1) * PAGE_LENGTH, PAGE_LENGTH);
			count = Test.count();
		}

		request.setAttribute("tests", tests);
		request.setAttribute("page", page);
		request.setAttribute("pageCount", count / PAGE_LENGTH);
	}

}
